package com.imooc.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;

/**
 * 单向加密：消息摘要算法加密
 * @author Administrator
 *
 */
public class ImoocMd {
	private String srcStr = "imooc security md";
	
	/**
	 * JDK实现MD5
	 */
	@Test
	public void jdkMd5(){
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md.digest(srcStr.getBytes());
			//将byte数组转成16进制；
			String md5Str = Hex.encodeHexString(md5Bytes);
			System.out.println("JDK MD5:"+md5Str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * JDK实现MD2
	 */
	@Test
	public void jdkMd2(){
		try {
			MessageDigest md = MessageDigest.getInstance("MD2");
			byte[] md2Bytes = md.digest(srcStr.getBytes());
			//将byte数组转成16进制；
			String md2Str = Hex.encodeHexString(md2Bytes);
			System.out.println("JDK MD2:"+md2Str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	/**
	 * bc,md5
	 */
	@Test
	public void bcMd5(){
		Digest digest = new MD5Digest();
		digest.update(srcStr.getBytes(), 0, srcStr.length());
		byte[] md5Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md5Bytes, 0);
		String md5Str = org.bouncycastle.util.encoders.Hex.toHexString(md5Bytes);
		System.out.println(" BC MD5:"+md5Str);
		
	}

	/**
	 * bc,md4
	 */
	@Test
	public void bcMd4(){
		Digest digest = new MD4Digest();
		digest.update(srcStr.getBytes(), 0, srcStr.length());
		byte[] md4Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md4Bytes, 0);
		String md4Str = org.bouncycastle.util.encoders.Hex.toHexString(md4Bytes);
		System.out.println(" BC MD4:"+md4Str);
		
	}
	
	/**
	 * bc,md4:方法2
	 */
	@Test
	public void bcMd42(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md = MessageDigest.getInstance("MD4");
			byte[] md4Bytes = md.digest(srcStr.getBytes());
			//将byte数组转成16进制；
			String md4Str = Hex.encodeHexString(md4Bytes);
			System.out.println("BC的MD4方法2:\n BC MD4:"+md4Str);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	/**
	 * cc,md5
	 */
	@Test
	public void ccMd5(){
		String md5Str = DigestUtils.md5Hex(srcStr.getBytes());
		System.out.println("CC MD5:"+md5Str);
	}
	/**
	 * cc,md2
	 */
	@Test
	public void ccMd2(){
		String md2Str = DigestUtils.md2Hex(srcStr.getBytes());
		System.out.println("CC MD2:"+md2Str);
	}
	
}
